<template>
	<div class="system-add-menu-container">
		<el-dialog title="新增菜单" v-model="state.isShowDialog" width="50%">
			<el-form :model="state.ruleForm" size="default" label-width="80px" ref="formRef" label-position="left">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb10">
						<el-form-item label="上级菜单">
							<el-cascader
								:options="state.menuData"
                :props="{checkStrictly: true}"
								placeholder="请选择上级菜单"
								clearable
								class="w100"
								v-model="state.ruleForm.parentid"
							>
								<template #default="{ node, data }">
									<span>{{ data.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>

							</el-cascader>
						</el-form-item>
					</el-col>
				
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
						<el-form-item label="菜单名称">
							<el-input v-model="state.ruleForm.title" placeholder="格式：message.router.xxx" clearable></el-input>
						</el-form-item>
					</el-col>
        
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
            <el-form-item label="路由名称">
              <el-input v-model="state.ruleForm.name" placeholder="路由中的 name 值" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
            <el-form-item label="路由路径">
              <el-input v-model="state.ruleForm.path" placeholder="路由中的 path 值" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
            <el-form-item label="重定向">
              <el-input v-model="state.ruleForm.redirect" placeholder="请输入路由重定向" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
            <el-form-item label="菜单图标">
              <IconSelector placeholder="请输入菜单图标" v-model="state.ruleForm.icon" type="all" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
            <el-form-item label="组件路径">
              <el-input v-model="state.ruleForm.component" placeholder="组件路径" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
            <el-form-item label="链接地址">
              <el-input v-model="state.ruleForm.linkUrl" placeholder="外链/内嵌时链接地址（http:xxx.com）" clearable :disabled="!state.ruleForm.isLink">
              </el-input>
            </el-form-item>
          </el-col>
       
            
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb10">
						<el-form-item label="菜单排序">
							<el-input-number v-model="state.ruleForm.sort" controls-position="right" placeholder="请输入排序" class="w100" />
						</el-form-item>
					</el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" >
            <el-form-item label="是否隐藏">
              <el-radio-group v-model="state.ruleForm.hidden">
                <el-radio :label="true">隐藏</el-radio>
                <el-radio :label="false">不隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="页面缓存">
								<el-radio-group v-model="state.ruleForm.isKeepAlive">
									<el-radio :label="true">缓存</el-radio>
									<el-radio :label="false">不缓存</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否固定">
								<el-radio-group v-model="state.ruleForm.isAffix">
									<el-radio :label="true">固定</el-radio>
									<el-radio :label="false">不固定</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否外链">
								<el-radio-group v-model="state.ruleForm.isLink" :disabled="state.ruleForm.isIframe">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否内嵌">
								<el-radio-group v-model="state.ruleForm.isIframe" @change="onSelectIframeChange">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>

            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="上传图片">
                <uploadSigle v-model="state.photoSrc" dialogWidth="30%"></uploadSigle>
							</el-form-item>
						</el-col>

            <el-divider border-style="dashed" />
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-button size="small" type="success" class="mb10" @click="onAddRow"><el-icon><ele-CirclePlus /></el-icon> 添加</el-button>

              <el-table :data="state.ruleForm.actions" style="width: 100%" :max-height="200">
                <el-table-column label="#" width="60">
                  <template #default="scope">
                    <div style="display: flex">
                      {{scope.$index+1}}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="权限名称" width="180">
                  <template #default="scope">
                    <div style="display: flex">
                      <el-input v-model="scope.row.name" placeholder="权限名称" clearable></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="权限编码" width="320">
                  <template #default="scope">
                    <div style="display: flex">
                      <el-input v-model="scope.row.uri" placeholder="权限编码" clearable></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="right">
                  <template #default="scope">
                    <el-button size="small" type="danger" @click="onDelRow(scope)"><el-icon><ele-Delete /></el-icon></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
				</el-row>

       
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, onMounted, defineComponent ,ref} from 'vue'
import {FormInstance} from 'element-plus'
import { storeToRefs } from 'pinia'
import { useRoutesList } from '/@/stores/routesList'
import { i18n } from '/@/i18n/index'
import IconSelector from '/@/components/iconSelector/index.vue'
import { menusApi } from '/@/api/system/menus'
import { success,error ,confirm} from '/@/utils/msg'
import uploadSigle from '/@/components/upload/index.vue'
// import { setBackEndControlRefreshRoutes } from "/@/router/backEnd"

  const formRef = ref()
  const stores = useRoutesList()
  const { routesList } = storeToRefs(stores)
  const state = reactive({
    isShowDialog: false,
    // 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
    ruleForm: {
      parentid: [], // 上级菜单
      name: '', // 路由名称
      component: '', // 组件路径
      sort: 0, // 菜单排序
      path: '', // 路由路径
      redirect: '', // 路由重定向，有子集 children 时
      title: '', // 菜单名称
      linkUrl : '',
      icon: '', // 菜单图标
      hidden: false, // 是否隐藏
      isKeepAlive: true, // 是否缓存
      isAffix: false, // 是否固定
      isLink: false, // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
      isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
      actions: [{
        id:0,
        name:'',
        uri: '',
      }]
    },
    menuData: [], // 上级菜单数据
    photoSrc:''
  })
  // 获取 vuex 中的路由
  const getMenuData = (routes: any) => {
    const arr: any = []
    routes.map((val: any) => {
      val['title'] = val.label//i18n.global.t(val.title)
      val['id'] = val.id
      arr.push({ ...val })
      if (val.children) getMenuData(val.children)
    })
    return arr
  }

  const emit = defineEmits<{
		(e:"on-load"):void
	}>()

  // 打开弹窗
  const openDialog = () => {
    state.isShowDialog = true
    state.ruleForm = {
      parentid: [0],name: '', component: '', sort: 0,path: '',redirect: '',title: '',linkUrl : '',icon: '',
      hidden: false,isKeepAlive: true,isAffix: false,isLink: false,isIframe: false,
      actions: [{id:0,name:'',uri: ''}]
    }
  }

  // 编辑
  const editDialog = async(id:number)=>{
    const {code,msg,data} = await menusApi().detail(id)
    if ( code == 0 || code == true) {
      state.ruleForm = data
    }
    state.isShowDialog = true
  }

  // 关闭弹窗
  const closeDialog = () => {
    state.isShowDialog = false
  }
  // 是否内嵌下拉改变
  const onSelectIframeChange = () => {
    if (state.ruleForm.isIframe) state.ruleForm.isLink = true
    else state.ruleForm.isLink = false
  }
  // 取消
  const onCancel = () => {
    closeDialog()
  }
  // 新增
  const onSubmit = async() => {
    console.log('pic',state.photoSrc)
    return false
    const {code,msg} = await menusApi().save(state.ruleForm)
    if ( code == true || code == 0 ) {
      closeDialog()
      emit('on-load')
      success(msg)
    } else {
      error(msg)
    }
    
  }
  // 页面加载时
  onMounted(async() => {
    const {code,data} = await menusApi().cascader_menus_data()
    state.menuData = getMenuData(data)
  })



  // 新增行
  const onAddRow = () => {
    state.ruleForm.actions.push({
      id: 0,
      name: '',
      uri: '',
    })
  }

  // 删除行
  const onDelRow = ( scope ) => {
    let respCode = 1
    if ( scope.row.id ) {
      confirm('确认删除菜单权限?').then(async()=>{
        const { code } = await menusApi().delete_action(scope.row.id)
        respCode = code
      }).catch(() => { })

    } 
    if (scope.row.id == 0 || respCode == 0 )
      state.ruleForm.actions.splice(scope.$index, 1)
  }

  defineExpose({
    openDialog,
    editDialog,
    ...toRefs(state)
  })

</script>
